package com.xiaoboframework.config.websocket;

import org.apache.commons.lang3.StringUtils;
import org.springframework.http.server.ServerHttpRequest;
import org.springframework.http.server.ServerHttpResponse;
import org.springframework.stereotype.Component;
import org.springframework.web.socket.WebSocketHandler;
import org.springframework.web.socket.server.HandshakeInterceptor;

import java.util.Map;

/**
 * @author: <a href="get_xiaobo@163.com">Josh_Xu</a>
 * @description:
 * @create: 2020-05-22 15:39
 **/
@Component
public class WebSocketInterceptor implements HandshakeInterceptor {

    @Override
    public boolean beforeHandshake(ServerHttpRequest request, ServerHttpResponse response, WebSocketHandler webSocketHandler, Map<String, Object> map) throws Exception {
        String path = request.getURI().getPath();
        String[] split = StringUtils.split(path,'/');
        if(split.length!=2){
            return false;
        }
        if(!StringUtils.isNumeric(split[1])){
            return false;
        }
        map.put("uid",Long.valueOf(split[1]));
        return true;
    }

    @Override
    public void afterHandshake(ServerHttpRequest serverHttpRequest, ServerHttpResponse serverHttpResponse, WebSocketHandler webSocketHandler, Exception e) {

    }
}
